﻿using DidaCode.Workflow.Logs;
using DidaCode.Workflow.Models;
using DidaCode.Workflow.Models.Parameters;
using DidaCode.Workflow.Models.Results;
using DidaCode.Workflow.NodeAttribute;
using DidaCode.Workflow.NodeBase;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace DidaCode.Workflow.Nodes
{
    [NodeType(Node.RatePlan)]
    public class RatePlan : NodeBase<HotelSearchParameter, HotelSearchResult>
    {

        [AutoMap(Node.HotelSearch)]
        public string HotelName { get; set; }

        [AutoMap(Node.RateAdjust)]
        public RateAdjustResult RateAdjustResult  { get; set; }


        [AutoMap(Node.RatePlan)]
        public List<string> RatePlans { get; set; }

        public RatePlan(string switchConfig) : base(switchConfig) { }


        public override bool ShouldExecute()
        {
            // 记录执行结果
            if (ExecutionLogger.TryGetResult<string>(Node.RateAdjust, out var RateAdjustNodeResult))
            {
                //Console.WriteLine($"在RatePlan中得到RateAdjustNode的首个结果:{RateAdjustNodeResult},允许执行");
                return true;
            }
            return false;
        }

        protected override async Task<NodeResult<HotelSearchResult>> ExecuteNodeAsync(ExecutionContext<HotelSearchParameter, HotelSearchResult> context)
        {

            await Task.Delay(100); // 模拟异步操作
            RatePlans = new List<string> { "RatePlan1", "RatePlan2", "RatePlan3" };
            context.Output.RatePlanResult = RatePlans;

            StringBuilder sb = new StringBuilder();
            sb.AppendLine("***************RatePlan开始********************");
            sb.AppendLine($"[Thread: {Thread.CurrentThread.ManagedThreadId}]");
            sb.AppendLine("RatePlan节点执行前的上下文信息:");
            sb.AppendLine($"{Node.HotelSearch}节点HotelName:{HotelName}");
            sb.AppendLine($"{Node.RateAdjust}节点Margin:{RateAdjustResult.RateAdjustMargin}");
            sb.AppendLine($"{Node.RatePlan}节点RatePlan条数:{RatePlans.Count}");
            sb.AppendLine("***************RatePlan结束********************");
            Console.WriteLine(sb.ToString());
            ExecutionLogger.LogResult(Node.RatePlan, new TypedResult(typeof(List<string>), RatePlans));
            return NodeResult<HotelSearchResult>.SuccessNode(context.Output);
        }
    }
}
